import {useEffect, useRef, useState} from 'react';
import {Button, Card, Col, Flex, Form, FormProps, Row, Select, Statistic} from 'antd';
import {getHistoryData} from "./utils/http.ts";
import useApp from "antd/es/app/useApp";
import dayjs from "dayjs";
import * as echarts from 'echarts';

type History = [[Date, number]];


const HistoryDataPage = ({cities, attributes, setCurrentCity}: any) => {
    const [loading, setLoading] = useState<boolean>(false);
    const [historyData, setHistoryData] = useState<History | null>(null);
    const chartRef = useRef<HTMLDivElement>(null);
    const {message} = useApp()


    useEffect(() => {
        const times = historyData?.map(value => (dayjs(value[0]).format('YYYY-MM-DD')));
        const values = historyData?.map(value => (value[1]))

        const myChart = echarts.init(chartRef.current);
        const option = {
            title: {
                text: '历史趋势数据'
            }, tooltip: {
                trigger: 'axis'
            }, legend: {
                data: ['历史']
            }, grid: {
                left: '3%', right: '4%', bottom: '3%', containLabel: true
            }, toolbox: {
                feature: {
                    saveAsImage: {}
                }
            }, xAxis: {
                type: 'category', boundaryGap: false, data: times
            }, yAxis: {
                type: 'value'
            }, series: [{
                name: '历史', type: 'line', stack: 'Total', data: values
            }]
        };
        myChart.setOption(option);
        return () => {
            myChart.dispose();
        }
    }, [historyData]);


    type FieldType = {
        cityName?: string; attribute?: string;
    };

    const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
        message.success("提交成功")
        setLoading(true);
        if (values.cityName && values.attribute) {
            try {
                const res: any = await getHistoryData(values.cityName, values.attribute);
                setHistoryData(res)
            } catch (error) {
                message.error("服务器异常");
                setLoading(false);
            }
        }

        setLoading(false);
    };

    const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
        console.log('Failed:', errorInfo);
        setLoading(false);
    };


    return (<Flex style={{flexDirection: 'column', margin: "10px", overflow: "hidden"}} gap={"middle"}>
            <Card>
                <Form
                    name="basic"
                    labelCol={{span: 2}}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item<FieldType>
                        label="城市"
                        name="cityName"
                        rules={[{required: true, message: '请选择城市'}]}
                    >
                        <Select
                            onSelect={(value: string) => {
                                console.log(`selected ${value}`);
                                setCurrentCity(value);
                            }}
                            options={cities}
                        />
                    </Form.Item>

                    <Form.Item<FieldType>
                        label="属性"
                        name="attribute"
                        rules={[{required: true, message: '请选择属性'}]}
                    >
                        <Select
                            options={attributes}
                        />
                    </Form.Item>

                    <Form.Item label={null}>
                        <Button type="primary" htmlType="submit" loading={loading}>
                            查看
                        </Button>
                    </Form.Item>
                </Form>
            </Card>
            <Card>
                <Row gutter={16}>
                    <Col span={12}>
                        <Statistic
                            title="历史数据点数"
                            value={historyData ? historyData.length : "暂无数据"}
                        />
                    </Col>
                    <Col span={12}>
                        <Statistic
                            title="最新数值"
                            value={historyData ? historyData[historyData.length - 1][1] : "暂无数据"}
                            precision={4}
                        />
                    </Col>
                </Row>
            </Card>
            <Card>
                <div ref={chartRef} style={{height: "500px", width: "100%"}}></div>
            </Card>
        </Flex>);
};

export default HistoryDataPage;
